<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import CodeMirror from 'vue-codemirror6'
import lastyear from 'last-year-components'
// import { json } from '@codemirror/lang-json';
// import { vue } from '@codemirror/lang-vue';
// import { javascript } from '@codemirror/lang-javascript';
import { html } from '@codemirror/lang-html';
import { nextTick } from 'vue';
const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})
const code = ref({})
const initType = async () => {
  const str = (import.meta as any).glob('../html/*.js')
  for (const path in str) {
    const component = (await str[path]()).default
    if (component.name) {
      code.value[component.name] = component.html
    }
  }

  codeVal.value = code.value[props.type]
}


// 初始化
let codeVal = ref('');
// json
const lang = html();
// 主题样式设置
const theme = {
  "&": {
    color: "#000",
    fontSize: "12px",
    backgroundColor: "#fefefe"
  },
  ".cm-content": {
    caretColor: "#0e9"
  },
  "&.cm-focused .cm-cursor": {
    borderLeftColor: "#0e9"
  },
  "&.cm-focused .cm-selectionBackground, ::selection": {

    backgroundColor: "#ddd !important"
  },
  ".cm-gutters": {//行号
    backgroundColor: "#e3f9fd",
    color: "#000",
    border: "none"
  },
  ".cm-selectionBackground": {//选中的内容背景色
    backgroundColor: "#ddd"
  },
  ".cm-selectionMatch": {
    backgroundColor: "#333"
  }
}
const initIframe = () => {
  const iframe = document.querySelector('#exampleIframe') as any
  iframe.addEventListener('load', () => {
    //将lastyear挂载到iframe的window上
    console.log(iframe.contentWindow)
    console.log(lastyear)
    iframe.contentWindow.postMessage(JSON.stringify(lastyear), '*');
  })
}

initType()

onMounted(() => {
  // initIframe()
})
watch(() => props.type, (val) => {
  if (props.type) {
    codeVal.value = code[props.type]
  }
})
</script>

<template>
  <div class="main">
    <code-mirror basic class="edit" :lang="lang" v-model="codeVal" :theme="theme" />
    <div class="content">
      <iframe id="exampleIframe" :srcdoc="codeVal" width="100%" height="100%"></iframe>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 80vh;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .content {
    width: 49%;
    height: 100%;
    border: 1px solid #eee;
  }

  .edit {
    width: 49%;
    height: 100%
  }
}

/* required! */
:deep(.cm-editor) {
  height: 100%;
}
</style>
